package main

import (
	"context"
	"fmt"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
	"userop_bff/global"
	_ "userop_bff/initialize"
	"userop_bff/router"
)

func main() {
	zap.S().Info(global.ServerConfig)
	initRouter := router.InitRouter()
	srv := &http.Server{
		Addr:    fmt.Sprintf("%s:%d", global.ServerConfig.IP, global.ServerConfig.Port),
		Handler: initRouter,
	}
	go func() {
		err := srv.ListenAndServe()
		if err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	//优雅的退出
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit
	timeout, cancelFunc := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancelFunc()
	err := srv.Shutdown(timeout)
	if err != nil {
		log.Fatal("Server Shutdown:", err)
	}

	//consul服务注销
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", global.ServerConfig.ConsulConfig.ConsulHost, global.ServerConfig.ConsulConfig.ConsulPort)
	//实例化
	client, err := api.NewClient(config)
	if err != nil {
		zap.S().Panic(err)
	}
	err = client.Agent().ServiceDeregister(global.ServerID)
	if err != nil {
		zap.S().Info("服务注销失败")
	}
	zap.S().Info("服务注销成功")
}
